﻿using System;
using System.Threading;
using System.Windows;

namespace FESSC_WORKBENCH_SERVER
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private Thread testThread;

        public MainWindow()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            AppVar.log = new ECLogger.Logger();
            string logfile = Environment.CurrentDirectory + "\\server.log";
            AppVar.log.setLogLevel(ECLogger.Logger.LOG_LEVEL.DEBUG);
            AppVar.log.Init(logfile, TB_LOG);
            AppVar.log.Info("*** FESSC WORKBENCH SERVER ***");
            try
            {
                //Connect to database.
                AppVar.log.Info("Connecting to database ...");
                AppVar.db = new DB("127.0.0.1", "sa", "//r00t//", "FESSC");
                AppVar.db = DB.getInstance();
                AppVar.log.Info("Database connected.");
                //Create ECMQ Server
                AppVar.usertoken = new FESSC_MESSAGE.UserToken();
                AppVar.mqworker= new MQWorker(AppVar.log);
                AppVar.mqserver = AppVar.mqworker.mqserver;
                AppVar.log.Info("EC Message Queue Server side created.");
                var srvinfo = AppVar.mqworker.mqserver.getServerInfo();
                AppVar.log.Info("Server Info:\r\nBind Address\t\t{0}\r\nListening Port\t\t{1}\r\n" +
                    "Buffer Size\t\t{2}\r\nMax Connections\t{3}\r\nCurrent Connections\t{4}",
                    srvinfo.bindIp, srvinfo.listenPort, srvinfo.bufferSize,
                    srvinfo.maxConnections, srvinfo.currentConnections);
                AppVar.mqworker.startMessageLoop();
                AppVar.usertoken = new FESSC_MESSAGE.UserToken();
                testThread = new Thread(new ThreadStart(testTh));
                testThread.Start();
            }
            catch (Exception ex)
            {
                AppVar.log.Error(ex.ToString());
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            AppVar.mqworker.close();
        }

        private void testTh()
        {
            try
            {
                AppVar.log.Info("Testing Database [Count users] ...");
                var testdb = AppVar.db.select();
                AppVar.log.Info("test db:{0}", testdb);
            }
            catch(Exception ex)
            {
                AppVar.log.Error(ex.ToString());
            }
        }

        public DB getDB()
        {
            return AppVar.db;
        }
    }
}